package util;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletResponse;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanArrayDataSource;

public class CollectionPDFReport {

	private String path;

	private Map<String, Object> parametros = new HashMap<String, Object>();

	private List<Map<String, Object>> dados = new ArrayList<Map<String, Object>>();

	private ServletResponse response;

	public ServletResponse getResponse() {
		return this.response;
	}

	public void setResponse(ServletResponse servletResponse) {
		this.response = servletResponse;
	}

	public String getPath() {
		return this.path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public void putParameter(String nome, Object valor) {
		this.parametros.put(nome, valor);
	}

	public void setParameter(Map<String, Object> parametros) {
		this.parametros = parametros;
	}

	public void setData(List<Map<String, Object>> dados) {
		this.dados = dados;
	}

	public void execute() throws Exception {
		try {
			JRDataSource dataSource = null;

			// Define a fonte de dados
			if (this.dados != null && (!this.dados.isEmpty())) {
				dataSource = new JRBeanArrayDataSource(this.dados.toArray());
			} else {
				dataSource = new JREmptyDataSource();
			}

			// Cria o relatório
			JasperPrint jasperPrint = JasperFillManager.fillReport(this.getPath(), parametros, dataSource);
			byte[] bytes = JasperExportManager.exportReportToPdf(jasperPrint);
			if (bytes != null) {
				this.response.setContentType("application/pdf");
				this.response.setContentLength(bytes.length);
				this.response.getOutputStream().write(bytes);
				this.response.getOutputStream().flush();
				this.response.flushBuffer();
			}
		} catch (Throwable e) {
			throw new Exception(e.getMessage());
		}
	}

	public void setConnection(Connection connection) {
	}
}